<template>
  <custom-drawer
    v-model="visible"
    title="同步接口"
    direction="rtl"
    with-header
    size="80%"
    icon="Compass"
    @confirm="handleSyncAllApi"
  >
    <div class="api-sync-container">
      <!-- Warning Alert -->
      <el-alert
        title="同步API，不输入路由分组将不会被自动同步，如果api不需要参与鉴权，可以按忽略按钮进行忽略。"
        type="warning"
        show-icon
        :closable="false"
      />

      <!-- New Route Section -->
      <div class="flex items-center gap-2 mt-3">
        <el-text>新增路由</el-text>
        <el-text size="small" style="color: rgb(107 114 128)">存在于当前路由中，但是不存在于api表</el-text>
      </div>

      <!-- API Table -->
      <el-table :data="apiRoutes.newApis">
        <el-table-column prop="path" label="API路径">
          <template #default="{ row }">
            <span class="font-mono">{{ row.path }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="apiGroup" label="API分组">
          <template #default="{ row }">
            <el-select v-model="row.apiGroup" allow-create filterable placeholder="请选择API分组" class="w-full">
              <el-option v-for="(item, index) in apiRoutes.apiGroups" :key="index" :value="item" :label="item" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="API简介">
          <template #default="{ row }">
            <el-input v-model="row.description" placeholder="输入API简介" :bordered="false" />
          </template>
        </el-table-column>

        <el-table-column prop="method" label="请求">
          <template #default="{ row }">
            <span class="text-sm">{{ row.method }}/{{ HttpMethodCN[row.method] }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" :width="200">
          <template #default="{ row }">
            <div class="flex gap-2">
              <el-button type="primary" link @click="handleAddApi(row)">
                <el-icon class="mr-1">
                  <Plus />
                </el-icon>
                单条新增
              </el-button>
              <el-button type="primary" link @click="handleIgnoreApi(row, 1)">
                <el-icon class="mr-1">
                  <CircleClose />
                </el-icon>
                忽略
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- New Route Section -->
      <div class="flex items-center gap-2 mt-3">
        <el-text>删除路由</el-text>
        <el-text size="small" style="color: rgb(107 114 128)">已经不存在于当前项目的路由中，确定同步后会自动从apis表删除</el-text>
      </div>

      <!-- API Table -->
      <el-table :data="apiRoutes.deleteApis">
        <el-table-column prop="path" label="API路径">
          <template #default="{ row }">
            <span class="font-mono">{{ row.path }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="apiGroup" label="API分组"></el-table-column>

        <el-table-column prop="description" label="API简介"></el-table-column>

        <el-table-column prop="method" label="请求">
          <template #default="{ row }">
            <span class="text-sm">{{ row.method }}/{{ HttpMethodCN[row.method] }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- New Route Section -->
      <div class="flex items-center gap-2 mt-3">
        <el-text>忽略路由</el-text>
        <el-text size="small" style="color: rgb(107 114 128)">忽略路由不参与api同步，常见为不需要进行鉴权行为的路由</el-text>
      </div>

      <!-- API Table -->
      <el-table :data="apiRoutes.ignoreApis">
        <el-table-column prop="path" label="API路径">
          <template #default="{ row }">
            <span class="font-mono">{{ row.path }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="apiGroup" label="API分组"></el-table-column>

        <el-table-column prop="description" label="API简介"></el-table-column>

        <el-table-column prop="method" label="请求">
          <template #default="{ row }">
            <span class="text-sm">{{ row.method }}/{{ HttpMethodCN[row.method] }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" :width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleIgnoreApi(row, 0)">
              <el-icon class="mr-1">
                <CircleClose />
              </el-icon>
              取消忽略
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </custom-drawer>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Plus, CircleClose } from "@element-plus/icons-vue";
import { CustomDrawer } from "@/components";
import type { Api } from "@/api/interface/api";
import { to } from "@/utils/result-handler";
import { addApi, batchCreateApi, ignoreApi, syncApi } from "@/api/modules/api";
import { HttpMethodCN } from "@/enums";

const visible = ref(false);

const apiRoutes = ref<Api.IApiSync>({
  newApis: [],
  deleteApis: [],
  ignoreApis: [],
  apiGroups: []
});
const getApiList = async () => {
  const result = await to(syncApi());
  if (!result.ok) return ElMessage.error("获取数据错误");
  apiRoutes.value = result.value.data;
};

// 新增api
const handleAddApi = async (row: Api.IApi) => {
  if (!row.apiGroup || !row.description) return ElMessage.error("请完善API的分组和简介");
  const result = await to(
    addApi({
      ...row,
      tags: row.apiGroup
    })
  );
  if (!result.ok) return;
  ElMessage.success("新增成功");
  await getApiList();
};

// 忽略api
const handleIgnoreApi = async (row: Api.IApi, ignore: number) => {
  const result = await to(
    ignoreApi({
      ...row,
      ignore
    })
  );
  if (!result.ok) return;
  ElMessage.success(ignore == 1 ? "忽略成功" : "取消成功");
  await getApiList();
};

// 新增所有的api接口
const handleSyncAllApi = async () => {
  // 判断接口的分组和描述是否填写
  for (const item of apiRoutes.value.newApis) {
    if (!item.apiGroup || !item.description) return ElMessage.error("请完善API的分组和简介");
    item.tags = item.apiGroup;
  }
  const result = await to(batchCreateApi(apiRoutes.value.newApis));
  if (!result.ok) return;
  ElMessage.success("同步成功");
  await getApiList();
};

const open = () => {
  visible.value = true;
  getApiList();
};

defineExpose({
  open
});
</script>

<style lang="scss" scoped>
.api-sync-container {
  box-sizing: border-box;
  width: 100%;
}
</style>
